package com.clp.inflxudb.core.flux_function;

import com.clp.inflxudb.core.Flux;
import com.influxdb.query.FluxRecord;
import com.influxdb.query.FluxTable;

import java.util.ArrayList;
import java.util.List;

/**
 * 计算最后时刻的值减去最先时刻的值
 */
public class CalcLastSubFirstFluxFuntion<T> implements ResultFluxFunction<CalcLastSubFirstFluxFuntion<T>, List<T>>{
    private String keyStr;
    private List<T> result;

    public CalcLastSubFirstFluxFuntion(String keyStr) {
        this.keyStr = keyStr;
        this.result = new ArrayList<>();
    }

    @Override
    public void doFunction(Flux flux) {
        flux.customClause(
                "\n\tfirst = data |> first(column: \"" + keyStr + "\")\n" +
                "\n\tlast = data |> last(column: \"" + keyStr + "\")\n" +
                "\n\tunion(tables: [first, last]) |> difference(columns: [\"" + keyStr + "\"]) ");
    }

    @Override
    public void afterQuery(List<FluxTable> fluxTableList) {
        if (fluxTableList == null || fluxTableList.isEmpty()) {
            throw new RuntimeException("（最后值与最先值的差值）查询失败！");
        }
        if (fluxTableList.size() > 1) {
            throw new RuntimeException("table的数量大于1！");
        }
//        InfluxClientX.convertFluxTables(fluxTableList)

        List<FluxRecord> records = fluxTableList.get(0).getRecords();
        records.forEach(record -> result.add((T) records.get(0).getValueByKey(keyStr)));
    }

    @Override
    public List<T> getResult() {
        return result;
    }

    @Override
    public CalcLastSubFirstFluxFuntion reSet() {
        this.result = new ArrayList<>();
        return this;
    }
}
